<?
/////////////////////////////////////////////////////////////////////////////////////////////////	
function get_conn(){
	global $db;


	$server = "localhost";
	$user ="ticostor_wuser";
	$pwd = "pr1nc3s4";
	$dbase="ticostor_main";		

	
	if($_SERVER['SERVER_NAME'] =="localhost"){
		$server = "localhost";
		$user ="root";
		$pwd = "";
		$dbase="genosha";		
	}
	
	//////////////////////	back handler	/core/recurring.php 
	if(substr($_SERVER['REQUEST_URI'],0,6) !='/core/'){
		if($_SESSION['REQUEST_URI'] != $_SERVER['REQUEST_URI']){
			$_SESSION['REQUEST_BACK'] = $_SESSION['REQUEST_URI'];
		}
		$_SESSION['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
	}
	//////////////////////	back handler	
	
	if($db ==''){
		@ $db=mysql_connect ($server, $user, $pwd);				
		if (!$db){		   
			error_handling("get_conn: ".$sql,mysql_error());			
		} 								
		mysql_select_db ($dbase); 
	}	
	
	//echo $_SERVER['REQUEST_URI'];
	return $db;
}		
//////////////////////////////////////////////////////////////////////////////////////////////////	
function getStatus($value,$param){
	if ($value == $param)
		return "selected";
	else	
		return "";
}
//////////////////////////////////////////////////////////////////////////////////////////////////	
function dbcombo($value,$descripcion,$tabla,$nombre,$seleccionado,$order,$javascript,$extraitems){

		$sql= "select ".$value." as myvalue , ".$descripcion." as mydesc from ".$tabla." order by ".$order;
		
		$result = mysql_query($sql);
		$combo= " <select name='".$nombre."'  ".$javascript." id='".$nombre."'>";
		if($result){
			if(mysql_num_rows($result)>0){
				$data = $extraitems;
				$num_results = mysql_num_rows($result);
				  for ($i=0; $i <$num_results; $i++){		 
					$row = mysql_fetch_array($result);
					$selected="";
					$selected = getStatus($row["myvalue"],$seleccionado);										
					$data.= " <option value='".$row["myvalue"]."'".$selected." >".$row["mydesc"]."</option>";
				  }//for
			}else{
				$data.= " <option value='0'>No Disponible</option>";
			}
		}//if
		else{
			error_handling("dbcombo: ".$sql,mysql_error());
		}
		$combo.= $data."</select>";
		 if($data==""){
		 	$combo = $sql;
		 }
		 return $combo;
}//function 
	
//////////////////////////////////////////////////////////////////////////////////////////////////	
/*
select id as myvalue, desc as mydesc from ....
*/
function dbcombosql($sqlquery,$nombre,$seleccionado,$javascript,$extraitems){
	$result = mysql_query($sqlquery);
	$combo= " <select name='".$nombre."'".$javascript." class='contenido_forma'> ";
	$data = $extraitems;
	if($result){
		$num_results = mysql_num_rows($result);
		if($num_results>0){
		  for ($i=0; $i <$num_results; $i++){		 
			$row = mysql_fetch_array($result);
			$selected="";
			$selected = getStatus($row["myvalue"],$seleccionado);										
			$data.= " <option value='".$row["myvalue"]."'".$selected." >".$row["mydesc"]."</option>";
		  }//for
		}else{
			$data.= " <option value='0'>Not Available</option>";
		}
	}else{
		error_handling("dbcombosql: ".$sqlquery,mysql_error());
	}
	$combo.= $data."</select>";

	 return $combo;
}//function 
//////////////////////////////////////////////////////////
function format_date($date){
	if($date !=''){
		$date_array = explode('-',$date);
		//2009-12-24
		
		$new_date_a= $date_array[0];
		$new_date_m= $date_array[1];
		$new_date_d= $date_array[2];	
	
		$new_date = $new_date_d."-".$new_date_m."-".$new_date_a;
		return $new_date; 
	}else{
		return "ND";
	}
}

//////////////////////////////////////////////////////////
function un_format_date($date){
	if($date !=''){
		$date_array = explode('/',$date);
		// 12/09/2010
		
		$new_date_a= $date_array[1];
		$new_date_m= $date_array[0];
		$new_date_d= $date_array[2];	
	
		$new_date = $new_date_d."-".$new_date_m."-".$new_date_a;
		return $new_date; 
	}else{
		return "ND";
	}
}
//////////////////////////////////////////////////////////

function format_time($hora){

	$hora_array = explode(':',$hora);

	$hora=$hora_array[0];
	$mins=$hora_array[1];

	$acron = " AM";	
	if(abs($hora) > 12){
		$hora = $hora - 12;
		$acron = " PM";
	}

	$new_hora = $hora.":".$mins." ".$acron;
	return $new_hora;
}

//////////////////////////////////////////////////////////
function format($precio,$decimales){
	return  number_format( $precio,$decimales);	
}



////////////////////////////////////////////////////////////////////

function get_modules($cols,$id_rol){
	if($id_rol !=''){
		$sql ="select * from rol_modulo where id_rol=".$id_rol;
		$result = mysql_query($sql);
		if($result){
			while($row = mysql_fetch_array($result)){
				$modulos.=$row['id_modulo'].",";
			}
			$modulos = substr($modulos,0,(strlen($modulos)-1));
		}else{
			
			error_handling("get_modules: ".$sql,mysql_error());
		}
	}
	
	
	////////////////////////////////////////////////////////////////////
	$sql ="select cm.name,link, m.name , id_modulo
			from 
			modulos m, menu_categories cm
			where m.id_category = cm.id_category
			 order by m.name, cm.name ";
	$result = mysql_query($sql);
	if($result){
	    $counter=0;  
		while($row = mysql_fetch_array($result)){		
		$counter ++;
					 if($counter % 2 ==0){
									$class_ = "sub";
								}else{
									$class_ = "sub2";
								}  
								
			if($cat!=$row['nombre']){
				$data.="<tr>
							<td align='center' bgcolor='#CCCCCC'> 
								".$row['nombre']."
							</td>
						</tr>";
				$cat=$row['nombre'];
				
			}
			$data.="<tr class='".$class_."'>
						<td> 
							<input type='checkbox' name='id_modulo[]' value='".$row['id_modulo']."' id='r".$row['id_modulo']."' ".is_in_list($modulos,$row['id_modulo']).">
							<label for='r".$row['id_modulo']."'>".$row['name']."</label> 
						</td>
						<td> 
							<a class='ac_vinculo1' href='".$row['link']."' target='_blank'> ".$row['link']."</a>
						</td>						
					</tr>";
			
			
		}//while
		return "<table border='0'>".$data."</table>";
	}else{
		
		error_handling("get_modules: ".$sql,mysql_error());
	}
}
////////////////////////////////////////////////////////////////////

function get_roles($cols,$id_user,$filtro){
	if($id_user !=''){
		$sql ="select * from user_rol where id_user=".$id_user;
		$result = mysql_query($sql);
		if($result){
			while($row = mysql_fetch_array($result)){
				$roles.=$row['id_rol'].",";
			}
			$roles = substr($roles,0,(strlen($roles)-1));
		}else{
			
			error_handling("get_roles: ".$sql,mysql_error());
		}
	}
	
	
	////////////////////////////////////////////////////////////////////
	if($filtro !=''){
		$parts = explode(',',$filtro);
		if(count($parts)>1){
			for($i=0;$i<count($parts);$i++){
				$where .=" id_rol =".$parts[$i];
				if( ($i+1) != count($parts)){
					$where .=" or ";
				}
			}
			$where =" where ".$where;
			
		}else{
			$where =" where id_rol =".$filtro;
		}
	}

	
	$sql ="select * from rol ".$where;
	$result = mysql_query($sql);
	if($result){
		while($row = mysql_fetch_array($result)){
			if($counter ==0){
				$data.="<tr>";
			}
			$data.="<td><input type='checkbox' name='id_rol[]' value='".$row['id_rol']."' ".is_in_list($roles,$row['id_rol']).">".$row['name']."</td>";
			$counter++;
			if($counter ==$cols){
				$data.="</tr>";
				$counter =0;
			}
		}//while
		return "<table border='0' class='contenido_forma'>".$data."</table>";
	}else{
		
		error_handling("get_roles: ".$sql,mysql_error());
	}
}

////////////////////////////////////////////////
function get_my_roles($id_user){
	if($id_user !=''){
		$sql ="select * from user_rol where id_user=".$id_user;
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			$roles =$row['id_rol'];
			return $roles;
		}else{
			error_handling("get_my_roles: ".$sql,mysql_error());
		}
	}
}

/////////////////////////////////////////
function is_admin($id_user){
	$sql = "select count(id_user) as existe from user_rol where id_rol=1  and id_user=".$id_user;
	$result = mysql_query($sql);
	if($result){
		$row = mysql_fetch_array($result);
		if($row['existe'] > 0){
			return true;
		}else{
			return false;
		}
	}else{
		
		error_handling("is_admin: ".$sql,mysql_error());
	}
} 


///////////////////////////////////////////
function is_checked($searched,$selecteds){
	$selecteds_array = explode(',',$selecteds);
	for($i=0;$i<count($selecteds_array);$i++){
		if($searched == $selecteds_array[$i]){
			return "checked";
		}
	}
}
///////////////////////////////////
function error_handling($sql,$error){
	$to = "dontpanic@danramza.com";
	$head = "Error report from ".$_SERVER['SERVER_NAME'];

	foreach($_REQUEST as $key=>$value){
     $variables .= $key." =".$value."<br>";
    }
	
	foreach($_SESSION as $key=>$value){
     $session_vars .= $key." =".$value."<br>";
    }	


	$body=  $error." <br><br>Executed:<br>".$sql." <br><br>at ".date("l dS of F Y h:i:s A").
	"<br><br>Error in File: <br>".$_SERVER['PHP_SELF'].
	"<br><br>Request Vars<br>".$variables.
	"<br><br>Session Vars<br><br>".$session_vars;


	$headers .= "From:".$_SERVER['SERVER_NAME']."<info@danramza.com>\n";
	$headers .= "X-Sender: <info@danramza.com>\n";
	$headers .= "X-Mailer: PHP\n"; //mailer
	$headers .= "X-Priority: 3\n"; //1 UrgentMessage, 3 Normal
	$headers .= "Return-Path: <info@danramza.com>>\n";
	$headers .= "Content-Type: text/html; charset=iso-8859-1\n";

	$send_alerts = 0;
	if($send_alerts ==0){
		echo $body;		exit;
	}else{
		$x =mail($to, $head , $body ,$headers);
		$script ="<script>document.location.href='../error.php'</script>"; 	  
		echo $script;
		
	}
}


///////////////////////////////////////////////
function is_in_list($arts,$id_product){
	$arts_list= explode(',',$arts);
	for($i=0; $i < count($arts_list);$i++){
		if($arts_list[$i] == $id_product){
			return " checked ";
		}
	}
	return "";
}
///////////////////////////////////////////////
function is_in_list_array($arts_array,$id_product){
	for($i=0; $i < count($arts_array);$i++){
		if($arts_array[$i] == $id_product){
			return " checked ";
		}
	}
	return "";
}
////////////////////////////////////////////////////////////////////////////

function get_header(){
	$url= $_SERVER['REQUEST_URI'];
	$url_array = explode("/",$url);
	for($i=0;$i < (count($url_array) -2) ; $i++){
		$base.="../";
	}
	if($_SESSION['session_id_user'] !=''){
		$include = $base."resources/top_on.php";	
	}else{
		$include = $base."resources/top_off.php";
	}
	include($include);
}
////////////////////////////////////////////////////////////////////////////

function get_foother(){

	if($_SESSION['session_id_user'] !=''){
		$include = $base."resources/fot_on.php";	
	}else{
		$include = $base."resources/fot_off.php";
	}
	include($include);
}


/////////////////////////////////////////////////////////

function get_user_name($id){
	if($id!=''){
		$sql = "select name from users where id_user=".$id;
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			return $row['name'];
		}else{
			error_handling("get_user_name: ".$sql,mysql_error());
		}
	}
}

//////////////////////////////////////////////
  function add_roles($id_rol,$id_user){
	$sql="delete from user_rol where id_user=".$id_user;
	$result = mysql_query($sql);
	if(!$result){
		error_handling(__FUNCTION__.$sql,mysql_error());
	}
	$sql="INSERT INTO user_rol (id_rol, id_user) VALUES (".$id_rol.", ".$id_user.")";
	$result = mysql_query($sql);
	if(!$result){
		
		error_handling(__FUNCTION__.$sql,mysql_error());
	}
  }


/////////////////////////////////////////////////////////
function get_last(){
	return mysql_insert_id();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////



function check_session(){
	$referer = explode("/",$_SERVER['HTTP_REFERER']);
	$referer = $referer[count($referer)-1];
	$page = $_SERVER['SCRIPT_NAME'];

	$server =  $_SERVER['SERVER_NAME'];
	$kickout="<script>
				alert('Su sesion ha caducado, Por favor ingrese de nuevo');
				document.location.href='/';
			 </script>
			 <meta http-equiv='refresh' content='0;url=http://".$server."/'>";
			 
	
	if($_SESSION['session_id_user'] ==''){
		
		if( $_COOKIE['user'] !='' && $_COOKIE['pwd'] !=''){
			do_reconnect($_COOKIE['user'],$_COOKIE['pwd']);
		}else{
			echo "R ".$kickout; exit;
		}
	}else{
		$roles = $_SESSION['session_roles'];
		for($i=0 ; $i < count($roles); $i++){
			$roles_csv.=$roles[$i].",";
		}
		$roles_csv = substr($roles_csv,0,(strlen($roles_csv)-1));
	
		if($referer == '/menu.php' && is_exception($page)== false){
			$sql ="	select id_rol from rol_modulo rm, modulos m
					where m.file ='".$page."' and id_rol in (".$roles_csv.")
					and rm.id_modulo = m.id_modulo ";
			//echo $referer."-".$sql;
			$result = mysql_query($sql);
			if($result){
				if(mysql_num_rows($result)== 0){
					echo "Q ".$page.$kickout; exit;		
				}
			}else{
				error_handling(__FUNCTION__.$sql,mysql_error());
			}				
		}
	}
}





/////////////////////////////////////////////////////////////////////////////////////////////////	


function html_echo($text){
	$text = htmlspecialchars  ($text);
	$text = str_replace("\n","<br>",$text);	
	return $text;
}

function format_date_text($date){
	setlocale(LC_CTYPE, 'Spanish');
	//setlocale(LC_TIME, 'Spanish');	
	setlocale(LC_TIME, 'es_ES.UTF-8');
	//$fecha = date('Y-m-d');
	//return html_entity_decode(strftime('%A %d de %B del %Y', strtotime($date)));  
	return html_entity_decode(strftime('%d de %B del %y', strtotime($date)));  
}





////////////////////////////////////////////////////////////////////////////////
function get_text($id_contenido){
	
	if($id_contenido!=''){
		$sql = "select texto from contenido where id_contenido=".$id_contenido; 
		$result = mysql_query($sql);	
		if($result){
			$row = mysql_fetch_array($result);
			return htmlentities($row['texto']);
		}else{
			error_handling(__FUNCTION__.$sql,mysql_error());
		}	
	}
}

////////////////////////////////////////////////////////////////////////////////
function get_menu3($id_categoria){
	$sql = "select id_category ,name  from categories where category_status='A' order by level";
	
	$result = mysql_query($sql);
	if($result){
		while($row = mysql_fetch_array($result)){

			$data .="<li class='$class'>
						".html_entity_decode($row['name'])."
					 </li>";
		}//while
	}else{
		error_handling(__FUNCTION__.$sql,mysql_error());
	}

	return $data;       
}


////////////////////////////////////////////////////////////////////////////////////

function do_redirect($url){

    if (!headers_sent()){    //If headers not sent yet... then do php redirect
        header('Location: '.$url); 
    }else{                    
		$script ="<script>document.location.href='".$url."'</script>";
		echo $script;	 exit;
    }
	
}


////////////////////////////////////////////////////////////////////////////////////////////////////////

function log_this_shit($info){  
	
	$location_explode = explode("/",$_SERVER['SCRIPT_NAME']);

	if(count($location_explode) >= 3){
		$to_add = count($location_explode) -2;
		for($i=0; $i < $to_add; $i++){
			$pre_path .= "../"	;
		}
	}
	
	$myFile = $pre_path."logs/".date('Y-m-d').".html";
	if(!file_exists($myFile)){
		$ourFileHandle = fopen($myFile, 'w') or die("can't open file");
		fclose($ourFileHandle);
	}

	$fh = fopen($myFile, 'a+') or die("can't open file");
	
	fwrite($fh,"<br>-------------------------------------<br>".$_SERVER['SCRIPT_FILENAME']."<br><br>". date('H:i:s -->')."<br>");
	
	if(is_array($info)){
		ob_start();
		print_r($info);
		$var = ob_get_contents();
		ob_end_clean();
		fputs($fh,$var);
	}else{
		fwrite($fh,"<br>".$info."<br>");	
	}
	
	fclose($fh);
}
//////////////////////////////////////////////////////////////////////////////////////////	
function getNumImages($id_container){
	$i=0;
	if($id_container!=''){
		$sql ="select id_media, title from media m where m.media='imagen' and m.id_container = ".$id_container;
		$result = mysql_query($sql);
		if($result){
			while($row = mysql_fetch_array($result)){
				//$image_path = "file_storage/ads/".$id_container."/mini-".$row['title'];
				//if(file_exists($image_path) > 0){
				$i++;
				//}
			}
		}
	}
	return $i;
}


////////////////////////////////////////////////////////////////////////////////
function get_user_rol($id_user){
	if($id_user !=''){
		$sql = "select id_rol from user_rol where id_user=".$id_user;
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			return $row['id_rol'];
		}else{
			error_handling("get_user_rol: ".$sql,mysql_error());
		}		
	}
}	

////////////////////////////////////////////////////////////////////////////////
function get_owner($id_location){
	if($id_location !=''){
		$sql = "select id_user from users_access where id_location=".$id_location;
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			return $row['id_user'];
		}else{
			error_handling("get_owner: ".$sql,mysql_error());
		}		
	}
}	
////////////////////////////////////////////////////////////////////

function get_vehicules_sumary($id_location){
	if($id_location !=''){
		$sql = "select v.id_vehicule, v.id, v.notes from vehicules v where id_location=".$id_location." order by id";
		$result = mysql_query($sql);
		if($result){
			$quantity = mysql_num_rows($result);
			while($row = mysql_fetch_array($result)){
				$car_info = get_car_options_list($row['id_vehicule'])." - ".$row['notes'];
				$car_id_num_list .= "<a title=\"".$car_info."\" href='vehicules_form.php?id=".$row['id_vehicule']."&layer=sum_".$id_location."' onClick='$(this).modal({width:350, height:350}).open(); return false;'>Placa: ".$row['id']."</a> - ".$row['notes']."<br> ";
			}
			
			if($quantity ==0){
				$car_id_num_list ="Ninguno"; 
			}
		}else{
			error_handling("get_vehicules_sumary: ".$sql,mysql_error());
		}		
	}
	$add_link = "<a href='vehicules_form.php?id_location=".$id_location."&layer=sum_".$id_location."' onClick='$(this).modal({width:350, height:350}).open(); return false;'><img src='images/plus_icon.jpg' width='22' height='22' border='0' title='click para agregar' /></a>";	
	$link = " <div id='sum_".$id_location."'> ".$car_id_num_list." ".$add_link." </div>";	
	return $link;
}

///////////////////////////////////g/////////////////////////////////
function get_residents_sumary($id_location,$links='Y'){
	if($id_location !=''){
		$sql = "select  concat(r.name,' ',r.lastname,' ',r.lastname2) as name, r.id_resident, r.phone1 , r.phone2 , r.phone3
					from  residents r
					where 
					r.id_location = $id_location 
					order by name";
					
		$result = mysql_query($sql);
		if($result){
			$quantity = mysql_num_rows($result);
			while($row = mysql_fetch_array($result)){
				$telefono ="";
				
				if($row['phone1'] !='' ){
					$telefono = "Telefono: ".$row['phone1'];						
				}				
				if($row['phone2'] !='' ){
					$telefono .= " / ".$row['phone2'];	
				}	
				if($row['phone3'] !='' ){
					$telefono .= " / ".$row['phone3'];	
				}				
							
				if($links=='Y'){
					$resident_list .= "<a title=\"".$telefono."\" href='residents_form.php?id=".$row['id_resident']."&layer=res_".$id_location."&id_location=".$id_location."' >".htmlentities($row['name'])."</a><br> ";	
				}else{
					$resident_list .= htmlentities($row['name'])." <br> ";					
				}
				
			}
			
			if($quantity ==0){
				$resident_list ="Ninguno"; 
			}
			
		}else{
			error_handling("get_residents_sumary: ".$sql,mysql_error());
		}		
	}
	if($links=='Y'){
		$add_link = "<a href='residents_form.php?id_location=".$id_location."&layer=res_".$id_location."' ><img src='images/plus_icon.jpg' width='22' height='22' border='0' title='click para agregar' /></a>";	
	}
	$link = " <div id='res_".$id_location."'> ".$resident_list." ".$add_link." </div>";	

	return $link;
}

///////////////////////////////////g/////////////////////////////////
function get_visitors_sumary($id_location,$links='Y'){
	if($id_location !=''){
		$sql = "select * from `visitors` v where v.id_location = ".$_SESSION['session_id_location']." order by name";
		$result = mysql_query($sql);
		if($result){
			$quantity = mysql_num_rows($result);
			while($row = mysql_fetch_array($result)){
				$telefono ="";
				
				if($links=='Y'){
					$visitors_list .= "<a title=\"".$telefono."\" href='visitors_form.php?id=".$row['id_visitor']."&layer=res_".$id_location."&id_location=".$id_location."' >".htmlentities($row['name'])."</a>:&nbsp;".get_texto($row['reponse'])."<br> ";	
				}else{
					$visitors_list .= htmlentities($row['name'])." <br> ";					
				}
				
			}
			
			if($quantity ==0){
				$resident_list ="Ninguno"; 
			}
			
		}else{
			error_handling("get_residents_sumary: ".$sql,mysql_error());
		}		
	}
	if($links=='Y'){
		$add_link = "<a href='visitors_form.php?id_location=".$id_location."&layer=res_".$id_location."' ><img src='images/plus_icon.jpg' width='22' height='22' border='0' title='click para agregar' /></a>";	
	}
	$link = " <div id='res_".$id_location."'> ".$visitors_list." ".$add_link." </div>";	

	return $link;
}


////////////////////////////////////////////////////////////////////

function get_options($id_vehicule){
	if($id_vehicule !=''){
		$sql ="select id_option from vehicules_options_granted where id_vehicule=".$id_vehicule;
		$result = mysql_query($sql);
		if($result){
			while($row = mysql_fetch_array($result)){
				$options.=$row['id_option'].",";
			}
			$options = substr($options,0,(strlen($options)-1));
		}else{
			
			error_handling("get_options: ".$sql,mysql_error());
		}
	}
	
	$cols =1;
	$sql ="select * from vehicules_options ";
	$result = mysql_query($sql);
	if($result){
		while($row = mysql_fetch_array($result)){
			if($counter ==0){
				$data.="<tr>";
			}
			$data.="<td><input type='checkbox' name='id_option[]' value='".$row['id_option']."' id='r_".$row['id_option']."' ".is_in_list($options,$row['id_option'])."><label for='r_".$row['id_option']."'>".$row['name']."</label></td>";
			$counter++;
			if($counter ==$cols){
				$data.="</tr>";
				$counter =0;
			}
		}//while
		return "<table border='0' >".$data."</table>";
	}else{
		
		error_handling("get_options: ".$sql,mysql_error());
	}
}

////////////////////////////////////////////////////////////////////
function grant_access($id_location, $id_user){
	if($id_location !='' && $id_user !=''){
		$sql = "select id_ua from  users_access where id_location = ".$id_location." and id_user =".$id_user;			
		$result = mysql_query($sql);			
		if($result){			
			$row= mysql_fetch_row($result);  			
			if($row['id_ua'] >0){
				return ;
			}else{
				$sql = "INSERT INTO users_access (id_location,id_user) VALUES (".$id_location.",".$id_user.")";			
				$result = mysql_query($sql);			
				if(!$result){			
					error_handling('users_access.insert  - '.$sql,mysql_error());			
				}	
			}
		}else{			
			error_handling('users_access.select  - '.$sql,mysql_error());			
		}	
	}
}
////////////////////////////////////////////////////////////////////

function remove_access($id_location, $id_user){
	if($id_location !='' && $id_user !=''){
		$sql = "delete from  users_access where id_location = ".$id_location." and id_user =".$id_user;			
		$result = mysql_query($sql);			
		if(!$result){			
			error_handling('users_access.select  - '.$sql,mysql_error());			
		}	
	}
}
////////////////////////////////////////////////////////////////////

function get_owner_name($id_location){
	if($id_location !=''){
		$sql = "select u.name, u.id_user
				from `users_access` ua, `users` u , users_options_granted uog
				where 
				ua.id_location = $id_location and 
				ua.id_user = u.id_user and 
				uog.id_user = u.id_user and
				uog.id_option = 4 order by name";
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);

			if($row['name'] !=''){ 
				return $row['name'];
			}else{
				return "No Disponible";	
			}
		}else{
			error_handling("get_user_rol: ".$sql,mysql_error());
		}		
	}	
}

function get_owner_name_link($id_location){
	if($id_location !=''){
		$sql = "select concat(u.name,' ',u.lastname,' ',u.lastname2)as name, u.id_user, u.phone1
				from `users` u 
				where 
				u.id_location = $id_location ";
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			if($row['phone1'] !='' ){
				$telefono = "Telefono: ".$row['phone1'];	
			}else{
				$telefono = "";
			}
			
			if($row['name'] !=''){ 
				return "<a title='$telefono' href='users_form.php?id=".$row['id_user']."'>".htmlentities($row['name'])."</a>";
			}else{
				return "No Disponible";	
			}
		}else{
			error_handling("get_user_rol: ".$sql,mysql_error());
		}		
	}	
}

////////////////////////////////////////////////////////////////////

function get_car_options_list($id_vehicule){
	
	if($id_vehicule){
		$sql ="select vo.name
				from `vehicules_options` vo , `vehicules_options_granted` vog 
				where vo.id_option = vog.id_option and vog.id_vehicule = ".$id_vehicule;
		
		$result = mysql_query($sql);
		if($result){
			while($row = mysql_fetch_array($result)){
				$data.= $row['name'].", ";
			}//while
			
			$data = substr($data,0,strlen($data)-2);
			return $data;
		}else{
			
			error_handling("get_car_options_list: ".$sql,mysql_error());
		}	
	}
}




//////////////////////////////////////////////
  function save_options($id_option ,$id_resident){
	 
	$sql="delete from resident_options_granted where id_resident=".$id_resident;
	$result = mysql_query($sql);
	if(!$result){
		error_handling(__FUNCTION__.$sql,mysql_error());
	}
	
	if(is_array($id_option)){
		for($i=0; $i< count($id_option); $i++){
			$sql="INSERT INTO resident_options_granted (id_option, id_resident) VALUES (".$id_option[$i].", ".$id_resident.")";
			$result = mysql_query($sql);
			if(!$result){
				error_handling(__FUNCTION__.$sql,mysql_error());
			}			
		}	
	}elseif($id_option !=''){
		$sql="INSERT INTO resident_options_granted (id_option, id_resident) VALUES (".$id_option.", ".$id_resident.")";
		$result = mysql_query($sql);
		if(!$result){
			error_handling(__FUNCTION__.$sql,mysql_error());
		}
	}
  }
////////////////////////////////////////////////////////////////////
  
function get_type_amount($id_it){
	if($id_it !=''){
		$sql = "select base_amount from invoices_type where id_it=".$id_it;
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			return $row['base_amount'];
		}else{
			error_handling(__FUNCTION__." ".$sql,mysql_error());
		}		
	}	
} 

////////////////////////////////////////////////////////////////////

function get_pending_invoices_count($id_location){
	if($id_location !=''){
		$sql = "select count(id_invoice) as cant from invoices where istatus='P' and id_location=".$id_location;
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			if($row['cant'] > 0){
				return $row['cant'];	
			}else{
				return "Ninguna";	
			}
			
		}else{
			error_handling(__FUNCTION__." ".$sql,mysql_error());
		}		
	}	
} 
////////////////////////////////////////////////////////////////////

function get_pending_payments_count($id_location){
	if($id_location !=''){
		$sql = "select count(id_invoice) as cant from invoices where istatus='R' and id_location=".$id_location;
		$result = mysql_query($sql);
		if($result){
			$row = mysql_fetch_array($result);
			if($row['cant'] > 0){
				return $row['cant'];	
			}else{
				return "Ninguna";	
			}
			
		}else{
			error_handling(__FUNCTION__." ".$sql,mysql_error());
		}		
	}	
} 
////////////////////////////////////////////////////////////////////

function send_welcome_email($id_user){
	
	if($id_user !=''){
		$sql = " select * from users where id_user=".$id_user; 
		$result = mysql_query($sql);	
		if($result){
			$row = mysql_fetch_array($result);
			$id_user = $row['id_user'];
			$id_location = $row['id_location'];
			$email = $row['email'];
			$name = $row['name'];
			$passwd = $row['passwd'];
			$last_login = $row['last_login'];
			$last_ip = $row['last_ip'];
			$phone1 = $row['phone1'];
			$phone2 = $row['phone2'];
			$phone3 = $row['phone3'];
			$debug = $row['debug'];
			$ustatus = $row['ustatus'];
		}else{
			error_handling($sql,mysql_error());
		}

		
		
		$to = "dontpanic@danramza.com";
		$head = "Error report from ".$_SERVER['SERVER_NAME'];
	
		foreach($_REQUEST as $key=>$value){
		 $variables .= $key." =".$value."<br>";
		}
		
		foreach($_SESSION as $key=>$value){
		 $session_vars .= $key." =".$value."<br>";
		}	
	
	
		$body=  $error." <br><br>Executed:<br>".$sql." <br><br>at ".date("l dS of F Y h:i:s A").
		"<br><br>Error in File: <br>".$_SERVER['PHP_SELF'].
		"<br><br>Request Vars<br>".$variables.
		"<br><br>Session Vars<br><br>".$session_vars;
	
	
		$headers .= "From:".$_SERVER['SERVER_NAME']."<info@danramza.com>\n";
		$headers .= "X-Sender: <info@danramza.com>\n";
		$headers .= "X-Mailer: PHP\n"; //mailer
		$headers .= "X-Priority: 3\n"; //1 UrgentMessage, 3 Normal
		$headers .= "Return-Path: <info@danramza.com>>\n";
		$headers .= "Content-Type: text/html; charset=iso-8859-1\n";
	
		$send_alerts = 0;
		if($send_alerts ==0){
			echo $body;		exit;
		}else{
			$x =mail($to, $head , $body ,$headers);
			$script ="<script>document.location.href='../error.php'</script>"; 	  
			echo $script;
			
		}		
	}	
}

///////////////////////////////////////////////////////////////////////////////
function get_texto($id_contenido){
	$field_name = "texto";
	
	$sql = "select * from contenido where id_contenido=".$id_contenido; 
	$result = mysql_query($sql);	
	if($result){
		$row = mysql_fetch_array($result);
		$texto = $row[$field_name];
		if($texto ==''){
			$texto = "Texto editable usando el content manager - Ref: ".$id_contenido ." - ".$row['label'];
		}
		
		return utf8_encode(htmlentities($texto));
	}else{
		error_handling($sql,mysql_error());
	}	
}


///////////////////////////////////////////////////////////////////////////////
function get_fileal_number($id_location){
	if($id_location !=''){
		$sql = "select number from locations where id_location=".$id_location; 
		$result = mysql_query($sql);	
		if($result){
			$row = mysql_fetch_array($result);
			return $row['number'];
		}else{
			error_handling($sql,mysql_error());
		}	
	}
}

///////////////////////////////////////////////////////////////////////////////
function get_attached_file($id_payment){
	if($id_payment !=''){
		$sql = "select id_media from payments_attachment where id_payment=".$id_payment; 
		$result = mysql_query($sql);	
		if($result){
			$row = mysql_fetch_array($result);
			return $row['id_media'];
		}else{
			error_handling($sql,mysql_error());
		}	
	}
}

////////////////////////////////////////////////////////////////////////////


function dump_contenido (){
	$sql = "select * from `contenido` c where cstatus='A' order  by c.id_contenido";	
	$result = mysql_query($sql);
 	if($result){
		while($row=mysql_fetch_array($result)){

			$val =  htmlentities ($row['texto']);
			$val = str_replace("\t","",$val);	
			$val = str_replace("\r","<br>",$val);	
			$val = str_replace("\n","<br>",$val);			
			
			$val2 = htmlentities($row['texto2']);
			$val = str_replace("\t","",$val);	
			$val = str_replace("\r","<br>",$val);	
			$val = str_replace("\n","<br>",$val);			
			
			$val3 = htmlentities($row['texto3']);			
			$val = str_replace("\t","",$val);	
			$val = str_replace("\r","<br>",$val);	
			$val = str_replace("\n","<br>",$val);			

			$sp_code .= "\n \t \t \t \t  case ".$row['id_contenido']." : return \"".$val."\"; break;";
			$fr_code .= "\n \t \t \t \t  case ".$row['id_contenido']." : return \"".$val2."\"; break;";
			$en_code .= "\n \t \t \t \t  case ".$row['id_contenido']." : return \"".$val3."\"; break;";						
		}
 	}else{
 		error_handling('contenido.insert  - '.$sql,mysql_error());
 	}
	
	
$base_code = "<?php


				function get_texto_static(\$id){
						
					\$id_language = get_current_language();
					switch(\$id_language ){
						case 1 : 
							switch(\$id){
								$sp_code
							}break;
							
						case 2 : 
							switch(\$id){
								$fr_code
							}break;					
				
						case 3 : 
							switch(\$id){
								$en_code
							}break;					
					}	
				   }
				?>";
	
	$myFile = "../file_storage/lang/contenido.php";
	if(!file_exists($myFile)){
		$ourFileHandle = fopen($myFile, 'w+') or die("can't open file");
		fclose($ourFileHandle);
	}

	$fh = fopen($myFile, 'w+') or die("can't open file");
	
	fwrite($fh,$base_code);
	fclose($fh);
	
}
////////////////////////////////////////////////////////////////////////////

	
?>